﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Light_Calendar
{
    public class CalendarCache
    {
        private EventsData eventsData;
        private SortedDictionary<DateTime, List<CalendarEvent>> cache;

        public bool IsReminderCached { get; set; }

        public CalendarCache(EventsData data)
        {
            eventsData = data;
            eventsData.Updating += new EventsData.UpdateEventHandler(eventsData_Updating);
            cache = new SortedDictionary<DateTime, List<CalendarEvent>>();
            IsReminderCached = false;
        }

        private void eventsData_Updating(CalendarEvent e)
        {
            foreach (DateTime date in cache.Keys.ToArray())
                if (e.OccursOn(date))
                {
                    cache.Remove(date);
                    if (date >= DateTime.Today && date <= DateTime.Today.AddDays(30)) IsReminderCached = false;
                }
        }

        public bool IsCached(DateTime date)
        {
            return cache.ContainsKey(date);
        }

        public List<CalendarEvent> EventsOn(DateTime date)
        {
            if (!cache.ContainsKey(date))
                cache[date] = (from e in eventsData.Events where e.OccursOn(date) orderby e.Description select e).ToList();
            return cache[date];
        }
    }
}
